package com.funmi.lizip.controller;

import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.utils.HttpContextUtils;
import com.funmi.lizip.utils.SpringContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hahashujia
 */
@Api(tags = "附件上传")
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.upload.nama}")
    private String reurl;

    @ApiOperation(value = "多附件上传-纯附件上传", notes = "多附件上传")
    @PostMapping(value = "")
    public R upload(@RequestParam(value = "file") MultipartFile[] file) {
        /*Map<String, Object> map = new HashMap<>(4);
        map.put("file.size", file.length);
        map.put("file.name", Arrays.stream(file).map(MultipartFile::getOriginalFilename).collect(Collectors.toList()));*/
        ArrayList<String> strings = new ArrayList<>();
        if (!(new File(PathEnum.PATH.getText())).exists()) {
            new File(PathEnum.PATH.getText()).mkdirs();
        }
        Arrays.stream(file).forEach(files -> {
            try {
                files.transferTo(new File(PathEnum.PATH.getText() + "\\" + files.getOriginalFilename()));
                strings.add(files.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return R.success().data(strings);
    }




    @ApiOperation(value = "多附件上传-多附件多参数", notes = "多附件上传")
    @PostMapping(value = "/param")
    public R uploads(@RequestParam(value = "file") MultipartFile[] file) {
        ArrayList<String> strings = new ArrayList<>();
        String s = "src/main/resources/upload";
        if (!(new File(s)).exists()) {
            new File(s).mkdirs();
        }
        Arrays.stream(file).forEach(files -> {
            try {
                files.transferTo(new File(files.getOriginalFilename()));
                strings.add(files.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return R.success().data(strings);

    }

    //POST请求接口为/upload
    @PostMapping(value = "/upload",produces = "application/json;charset=utf-8")
    //@RequestParam指向前端input file的name,加入HttpServletRequest请求
    public R upload(@RequestParam("uploadFile") MultipartFile[] multipartFiles, HttpServletRequest request){
        //设置当前日期
        String uploaddate= new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //设置文件上传保存文件路径：保存在项目运行目录下的uploadFile文件夹+当前日期
        String savepath = request.getSession().getServletContext().getRealPath("/uploadFile/")+uploaddate;
        //创建文件夹,当文件夹不存在时，创建文件夹
        File folder = new File(savepath);
        if(!folder.isDirectory()){
            folder.mkdir();
        }
        //建立一个listmap的返回参数
        List<Map<String,Object>> listmap =new ArrayList<>();
        //建立一个循环分别接收多文件
        for(MultipartFile file:multipartFiles){
            //重命名上传的文件,为避免重复,我们使用UUID对文件分别进行命名
            String oldname=file.getOriginalFilename();//getOriginalFilename()获取文件名带后缀
            //UUID去掉中间的"-",并将原文件后缀名加入新文件
            String newname= UUID.randomUUID().toString().replace("-","")
                    +oldname.substring(oldname.lastIndexOf("."));
            //建立每一个文件上传的返回参数
            Map<String,Object> map=new HashMap<>();
            //文件保存操作
            try {
                file.transferTo(new File(folder,newname));
                //建立新文件路径,在前端可以直接访问如http://localhost:8080/uploadFile/2021-07-16/新文件名(带后缀)
                String filepath=request.getScheme()+"://"+request.getServerName()+":"+
                        request.getServerPort()+"/uploadFile/"+uploaddate+"/"+newname;
                //写入返回参数
                map.put("[oldname]",oldname);
                map.put("[newname]",newname);
                map.put("[filepath]",filepath);
                map.put("[result]","成功!");
                listmap.add(map);
            }catch (IOException ex){
                //操作失败报错并写入返回参数
                ex.printStackTrace();
                map.put("[oldname]",oldname);
                map.put("[newname]",newname);
                map.put("[filepath]","");
                map.put("[result]","失败!");
            }
        }
        //将执行结果返回
        return R.success().data(listmap);
    }

    }
